package cn.bookCity.servlet;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.bookCity.domain.Products;
import cn.bookCity.service.ProductService;
import cn.bookCity.util.BeanFactory;
import cn.bookCity.util.UUIDUtils;
import cn.bookCity.util.UploadUtils;

@WebServlet("/product")
public class ProductServlet extends BaseServlet {
	public String showAllProducts(HttpServletRequest request,HttpServletResponse response) {
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		List<Products> products=p.getAllBooks();
		request.setAttribute("products", products);
		return "/manager/productManage.jsp";
		
	}
	
	public String findProductById(HttpServletRequest request,HttpServletResponse response) {
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		String id = request.getParameter("id");
		Products product = p.getProduct(id);
		request.setAttribute("product", product);
		return "/manager/product.jsp";
	}
	
	public String modifyProductById(HttpServletRequest request,HttpServletResponse response) {
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		String id = request.getParameter("id");
		Products product = p.getProduct(id);
		request.setAttribute("product", product);
		return "/manager/modifyProduct.jsp";
	}
	
	public String modify(HttpServletRequest request,HttpServletResponse response) {
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		String id = request.getParameter("id");
		Products oldProduct = p.getProduct(id);
		String oldimgUrl = oldProduct.getImgurl();
		
        //删除书籍数据
		p.delProduct(id);
		//新建一个书籍对象，id不变。
		Products product = new Products();
		product.setId(id);
		product.setImgurl(oldimgUrl);
		DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
			List<FileItem> fileItemList = sfu.parseRequest(request);
			
			Map<String,String> map = new HashMap<String,String>();
			
			//区分表单域
            for (int i = 0; i < fileItemList.size(); i++) {
                FileItem item = fileItemList.get(i);
                
                //isFormField为true，表示这不是文件上传表单域
                if(!item.isFormField()&&!item.getName().equals("")){
                	//生成图片的url保存到数据库
                	String imgUrl = "images/book/"+UploadUtils.getUUIDName(UploadUtils.getRealName(item.getName()));
                	product.setImgurl(imgUrl);
                	//获取项目地址
                	String realUrl=request.getSession().getServletContext().getRealPath("/");
                	//保存图片 保存地址=项目地址+相对路径
                	File destFile = new File(realUrl+imgUrl);
					item.write(destFile);
					//删除书籍图片
					File file=new File(request.getSession().getServletContext().getRealPath("/")+oldimgUrl);
			        if(file.exists()&&file.isFile())
			            file.delete();
                }else {
                	map.put(item.getFieldName(), item.getString("UTF-8"));
				}
            }
            
            BeanUtils.populate(product, map);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        p.addProduct(product);
		
		return "/manager/productManage.jsp";
	}
	
	public String deleteProductById(HttpServletRequest request,HttpServletResponse response) {
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		String id = request.getParameter("id");
		p.delProduct(id);
		return "/manager/productManage.jsp";
	}
	
	public String addProduct(HttpServletRequest request,HttpServletResponse response) throws IllegalAccessException, InvocationTargetException {
		Products product = new Products();
		ProductService p=(ProductService)BeanFactory.getBean("ProductService");
		product.setId(UUIDUtils.getId());
		DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
			List<FileItem> fileItemList = sfu.parseRequest(request);
			
			Map<String,String> map = new HashMap<String,String>();
			
			//区分表单域
            for (int i = 0; i < fileItemList.size(); i++) {
                FileItem item = fileItemList.get(i);
                
                //isFormField为true，表示这不是文件上传表单域
                if(!item.isFormField()){
                	//生成图片的url保存到数据库
                	String imgUrl = "images/book/"+UploadUtils.getUUIDName(UploadUtils.getRealName(item.getName()));
                	product.setImgurl(imgUrl);
                	//获取项目地址
                	String realUrl=request.getSession().getServletContext().getRealPath("/");
                	//保存图片 保存地址=项目地址+相对路径
                	File destFile = new File(realUrl+imgUrl);
					item.write(destFile);
                }else {
                	map.put(item.getFieldName(), item.getString("UTF-8"));
				}
            }
            
            BeanUtils.populate(product, map);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//product.setImgurl();
        //封装bean
        
        p.addProduct(product);
		return "/manager/productManage.jsp";
	}
}
